package com.party.mobile.web.controller.crowdfund;

import com.google.common.base.Strings;
import com.party.authorization.annotation.Authorization;
import com.party.common.paging.Page;
import com.party.common.utils.PartyCode;
import com.party.core.model.crowdfund.Support;
import com.party.core.service.crowdfund.ISupportService;
import com.party.mobile.biz.crowdfund.ProjectBizService;
import com.party.mobile.biz.crowdfund.SupportBizService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.utils.excel.ExportExcel;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.crowdfund.input.SupportStatisticsInput;
import com.party.mobile.web.dto.crowdfund.output.SponsorOutput;
import com.party.mobile.web.dto.crowdfund.output.SupportOutput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 众筹支持控制器
 * Created by wei.li
 *
 * @date 2017/2/22 0022
 * @time 14:38
 */

@Controller
@RequestMapping(value = "crowdfund/support")
public class SupportController {

    @Autowired
    private ProjectBizService projectBizService;

    @Autowired
    private SupportBizService supportBizService;

    @Autowired
    private ISupportService supportService;

    @Autowired
    private CurrentUserBizService currentUserBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 众筹支持列表
     * @param page 分页参数
     * @param id 项目编号
     * @return 交互数据
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "list")
    public AjaxResult list(Page page, String id, HttpServletRequest request, String targetId) {
        AjaxResult ajaxResult = new AjaxResult();
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        //参数验证
        if (Strings.isNullOrEmpty(id)) {
            ajaxResult.setErrorCode(PartyCode.PARAMETER_ILLEGAL);
            ajaxResult.setDescription("项目编号不能为空");
            return ajaxResult;
        }

        try {
            List<SupportOutput> supportOutputList = projectBizService.listSupport(page, id, currentUser.getId(), targetId);
            return AjaxResult.success(supportOutputList, page);
        } catch (Exception e) {
            logger.error("支持者列表异常", e);
            return AjaxResult.error(100, "系统异常");
        }
    }


    /**
     * 统计
     * @param input 输入视图
     * @param result 验证参数
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "statistics")
    public AjaxResult statistics(@Validated SupportStatisticsInput input, BindingResult result) {
        try {
            if (result.hasErrors()) {
                List<ObjectError> allErrors = result.getAllErrors();
                String description = allErrors.get(0).getDefaultMessage();
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
            }

            supportBizService.statistics(input);

        } catch (Exception e) {
            logger.error("统计支持异常", e);
        }
        return AjaxResult.success();
    }

    /**
     * 众筹支持者列表
     * @param page
     * @param id 众筹项目ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "sponsorList")
    public AjaxResult sponsorList(Page page, String id) {
        AjaxResult ajaxResult = new AjaxResult();
        //参数验证
        if (Strings.isNullOrEmpty(id)) {
            ajaxResult.setErrorCode(PartyCode.PARAMETER_ILLEGAL);
            ajaxResult.setDescription("项目编号不能为空");
            return ajaxResult;
        }

        try {
            List<SponsorOutput> sponsorOutputList = projectBizService.sponsorListSimple(page, id);
            return AjaxResult.success(sponsorOutputList, page);
        } catch (Exception e) {
            logger.error("众筹支持者列表异常", e);
            return AjaxResult.error(100, "系统异常");
        }
    }

    /**
     * 导出Excel表
     * @param id
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "applyExport")
    public AjaxResult applyExport(String id, HttpServletResponse response){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = "支持者列表" + sdf.format(new Date()) + ".xlsx";
            List<SponsorOutput> sponsorOutputList = null;
            sponsorOutputList = projectBizService.sponsorList(null, id);
            new ExportExcel("支持者列表",SponsorOutput.class).setDataList(sponsorOutputList).write(response,fileName).dispose();
        } catch (Exception e) {
            e.printStackTrace();
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.setDescription("系统异常");
            return ajaxResult;
        }
        return null;
    }

    /**
     * 获取支持证书数据
     * @param id: 支持id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getDiplomaData")
    public AjaxResult getDiplomaData(String id) {
        return supportBizService.getDiplomaData(id);
    }


    /***
     * 支持者开关显示 修改
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "switchDisplay")
    public AjaxResult switchDisplay(String id, Integer supportSwitch) {
        try {
            Support support = supportService.get(id);
            support.setSupportSwitch(supportSwitch);
            supportService.update(support);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("支持者开关显示 修改 异常", e);
            return AjaxResult.error(100, "系统异常");
        }
    }
}
